/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.snda.dw.hiveapi.hiveapitest;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.concurrent.Callable;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author lidejia
 */
public class HiveJob implements Callable<HiveQueryResult> {

    private static final String HIVE_PATH = "/home/hadoop/lidejia/hive-0.7.0-cdh3u0/bin/hive";
    private String[] cmds = new String[]{HIVE_PATH, "-e", null};
    private HiveSession session = null;
    //

    public HiveJob(HiveSession session, String dbName, String querySQL) {
        this.session = session;
        String executeSQL = String.format("use %s; set hive.cli.print.header=true; %s;", dbName, querySQL);
        cmds[2] = executeSQL;
    }

    public HiveQueryResult call() throws Exception {
        HiveQueryResult result = null;
        try {
            ProcessBuilder pb = new ProcessBuilder(cmds);
            pb.redirectErrorStream(true);
            Process process = pb.start();
            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream(), "UTF-8"));
            try {
                HiveQueryResultParser parser = new HiveQueryResultParser(session);
                result = parser.parse(reader);
            } finally {
                reader.close();
            }
        } catch (Exception ex) {
            Logger.getLogger(HiveJob.class.getName()).log(Level.SEVERE, null, ex);
        }
        return result;
    }
}
